package com.szh.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: SongZiHao
 * @date: 2023/1/15
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    @ResponseBody
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }

    /**
     * 感知这次登录是从ssoserver登录成功之后跳转回来的
     * @param model
     * @param session
     * @param token 只要去ssoserver登录成功之后，就会带上这个token
     * @return
     */
    @GetMapping(value = "/boss")
    public String employees(Model model, HttpSession session,
                            @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) { //去ssoserver登录成功了，向ssoserver发请求获取真正的用户信息，存到session中
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://ssoserver.com:8080/getUserInfo?token=" + token, String.class);
            String userInfo = responseEntity.getBody();
            session.setAttribute("loginUser", userInfo);
        }
        Object attribute = session.getAttribute("loginUser");
        if (Objects.isNull(attribute)) { //没登录，跳转到登录服务器进行登录
            return "redirect:" + ssoServerUrl + "?redirect_url=http://client2.com:8082/boss";
        } else { //登录了
            List<String> bossList = new ArrayList<>();
            bossList.add("宋总");
            bossList.add("刘总");
            model.addAttribute("bossList", bossList);
            return "list";
        }
    }
}
